<script setup>
  import {register, login, getSignCode, googleLogin, facebookLogin} from '@/api/login'
  import useUserStore from '@/store/modules/user'
  import forgetPassword from './forgetPassword.vue'
  import Svg from './svg.vue'
  import { showToast } from 'vant'

  const userStore = useUserStore()
  const route = useRoute()
  const router = useRouter()
  const {proxy} = getCurrentInstance()


  // 登录、注册切换
  const isLogin = ref(true)
  const formRef = ref(null)
  const form = ref({})
  // 缓存跳转登录页的前一个路由
  const redirect = ref(undefined);
  const loading = ref(false)
  // 忘记密码
  const open = ref(false)
    // 控制发送验证码
    const isCode = ref(false)
  const time = ref(60)
  const timer = ref(null)

  watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  }, { immediate: true })

  function resetTimer() {
    isCode.value = false
    time.value = 60
    clearInterval(timer)
  }
  // 发送验证码
  function sendCode() {
    formRef.value.validate(['email']).then(() => {
      getSignCode({email: form.value.email}).then(() => {
        isCode.value = true
        timer.value = setInterval(() => {
          time.value--
          if(time.value===1) {
            resetTimer()
          }
        }, 1000)
      })
    })
  }
  // 切换登录和注册
  function switchFun() {
    isLogin.value = !isLogin.value
    formRef.value.resetValidation()
    form.value = {}
  }
  // 登录&注册
  function submitForm() {
    const fields = ['email', 'password', ...(isLogin.value?[]:['firstName', 'lastName', 'code'])]
    formRef.value.validate(fields).then(() => {
      const params = formRef.value.getValues()
      if(isLogin.value) {
        loading.value = true
        // 登录
        userStore.login(params).then(() => {
          const query = {}
          if(redirect.value) {
            const t = redirect.value.split("?")
            t.forEach((it) => {
                let j = it.split("=");
                query[j[0]] = j[1]
            })
          }
          router.push({ path: redirect.value || "/", query })
        }).catch(() => {
          loading.value = false;
        })
      } else {
        // 注册
        register(params).then(res => {
          showToast(proxy.$t('login.registerSuc'))
          // 注册完跳登录
          switchFun()
        })
      }
    }).catch(err => {
      throw(err)
    })
  }
  // 三方登录
  function otherLogin(type) {
    const api = type===1?googleLogin:facebookLogin
    api().then(r => {
      window.open(r.data, '_self')
    })
  }
  // 用户协议
  function toDeal() {
    router.push({path: '/agreement'})
  }
</script>

<template>
  <div class="p-login">
    <div class="main-con">
      <p class="m-title">{{`${isLogin?$t('login.registered'):$t('login.register')}`}}</p>
      <p class="sub-title">{{`${isLogin?$t('login.loginTip'):$t('login.registerTip')}`}}</p>
      <van-form
        ref="formRef"
        validate-trigger="['onSubmit']"
      >
        <c-input
          v-if="!isLogin"
          name="firstName"
          v-model:value="form.firstName"
          placeholder="First name*"
          :rules="[{ required: true, message: $t('login.firstNameTip') }]"
        />
        <c-input
          v-if="!isLogin"
          name="lastName"
          v-model:value="form.lastName"
          placeholder="Last name*"
          :rules="[{ required: true, message: $t('login.lastNameTip') }]"
        />
        <c-input
          name="email"
          v-model:value="form.email"
          :placeholder="`${$t('login.email')}*`"
          :rules="[
            { required: true, message: $t('login.emailTip') },
            {
              pattern: new RegExp(/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/),
              message: $t('login.emailTips'),
            }
          ]"
        />
        <c-input
          name="code"
          v-if="!isLogin"
          v-model:value="form.code"
          :placeholder="`${$t('login.code')}*`"
          :funIcon="true"
          :rules="[{ required: true, message: $t('login.codeTip')}]"
        >
            <van-button
              @click="sendCode"
              :disabled="isCode"
            >
              {{`${isCode?time+'s':$t('login.getCode')}`}}
            </van-button>
        </c-input>
        <c-input
          name="password"
          v-model:value="form.password"
          :placeholder="`${$t('login.password')}*`"
          type="password"
          :rules="[{ required: true, message: $t('login.passwordTip') }]"
        />
      </van-form>
      <p class="tip" v-if="isLogin" @click="open=true">{{$t('login.forgetPassword')}}？</p>
      <div class="login-box">
        <van-button
          class="login-btn s-btn"
          @click="submitForm"
          :loading="loading"
        >
          {{`${isLogin?$t('login.login'):$t('login.register')}`}}
        </van-button>
        <p class="r-tip">
          {{$t(`login.${isLogin?'no':'has'}Count`)}}，
          <span @click="switchFun">{{`${isLogin?$t('login.quickRegister'):$t('login.toLogin')}`}}</span>
        </p>
        <div class="parting-line" v-if="isLogin">
          <span>{{$t('login.otherLogin')}}</span>
        </div>
        <div class="other-type" v-if="isLogin">
          <Svg iconName='icon-guge'style="margin-right: 24px;" @click="otherLogin(1)"></Svg>
          <Svg iconName='icon-facebook' @click="otherLogin(2)"></Svg>
        </div>
        <p class="r-tip" v-else>
          {{$t('login.agree')}}
          <span @click="toDeal">{{$t('login.deal')}}</span>
        </p>
      </div>
    </div>
    <forget-password v-model="open"/>
  </div>
</template>

<style lang="scss" scoped>
.p-login {
  padding: 24px 16px;
  .main-con {
    .m-title {
      font-size: 18px;
      margin-bottom: 4px;
    }
    .sub-title {
      color: #8C8C8C;
      font-size: 14px;
      margin-bottom: 24px;
    }
    .tip {
      color: #8C8C8C;
      font-size: 12px;
      text-decoration: underline;
    }
    .login-box {
      .login-btn {
        margin: 32px 0 16px;
      }
      .r-tip {
        text-align: center;
        font-size: 14px;
        margin-bottom: 32px;
        span {
          text-decoration: underline;
        }
      }
      .parting-line {
        background: #E5E5E5;
        height: 1px;
        position: relative;
        margin-bottom: 24px;
        span {
          display: block;
          background: #FFFFFF;
          position: absolute;
          padding: 0 15px;
          top: -10px;
          left: calc(50% - 100px);
          font-size: 14px;
          color: #8C8C8C;
        }
      }
      .other-type {
        text-align: center;
      }
    }
  }
}
</style>